package com.saver.modules.sys.service;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 邮箱工具
 *
 * @author yuxiaolong
 * @email 1005471232@qq.com
 * @date 2019年03月01日 下午6:56
 */
@Component
public class MailService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    JavaMailSender jms;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.nick}")
    private String nick;

    /**
     * 发送文本邮箱
     *
     * @param to      收件人
     * @param subject 主题
     * @param text    文本
     * @return
     */
    public Boolean sendTextMail(String to, String subject, String text) {
        //建立邮件消息
        try {

            SimpleMailMessage mainMessage = new SimpleMailMessage();
            //发送者
            String s = MimeUtility.encodeText(nick);
            mainMessage.setFrom(s + " <" + username + ">");

            mainMessage.setSentDate(new Date());
            //接收者
            mainMessage.setTo(to);
            //发送的标题
            mainMessage.setSubject(subject);
            //发送的内容
            mainMessage.setText(text);
            jms.send(mainMessage);
            logger.info("发送邮箱成功to：" + to + ",主题：" + subject);
        } catch (Exception e) {
            logger.info("邮件发送失败to：" + to + ",主题：" + subject);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 发送html邮箱
     *
     * @param to      接收人
     * @param subject 主题
     * @param text    html
     * @return
     */
    public Boolean sendHtmlMail(String to, String subject, String text) {
        try {
            MimeMessage message = jms.createMimeMessage();
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String s = MimeUtility.encodeText(nick);
            helper.setFrom(s+" <"+username+">");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
            jms.send(message);
            logger.info("发送邮箱成功to：" + to + ",主题：" + subject);
        } catch (Exception e) {
            logger.info("邮件发送失败to：" + to + ",主题：" + subject);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 发送html模板邮箱
     *
     * @param tempName 模板名称
     * @param map      模板数据
     * @param to       接收人
     * @param subject  主题
     * @return
     */
    public Boolean sendHtmlTemplateMain(String tempName, Map<String, String> map, String to, String subject) {
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(  "mail/" + tempName);
            String html = IOUtils.toString(inputStream, "utf-8");
            Set<String> set = map.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                html = html.replace(next, map.get(next));
            }
            return sendHtmlMail(to, subject, html);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
